#include "hal_cs_f61_flash.h"

#include <stdio.h>

/******************************************************************************
@brief : Flash initialization
@param : NONE
*******************************************************************************/
void HAL_Flash_init(void)
{
	RCC_AHBPeriphClOCKCmd(RCC_AHBPeriph_ISP , ENABLE); //added by Eric.Chen 2015/05/09

	FMC_InitTypeDef FMC_InitStruct;

    	FMC_InitStruct.ISP_Freq = ISP_Freq_24MHz;
    	FMC_InitStruct.Enter_DeepStandby = DISABLE;
    	FMC_InitStruct.APROM_Update = ENABLE;
    	FMC_InitStruct.LDROM_Update = ENABLE;
    	FMC_InitStruct.CFG_Update = DISABLE;

    	FMC_Init(&FMC_InitStruct);
}

/*******************************************************************************
@brief : flash erase
@param : block      
	 offset   
	 size     
	 buf  
@ret   : 0 success     1 fail
@tips  : csa37fx60 512 Bytes/section   erase 512KB each time
*******************************************************************************/
uint32_t flash_erase_sector(uint16_t sectorNo)
{
	uint8_t ret  = 0;

	uint32_t addr = (uint32_t)(sectorNo) << 9;

	if( FMC_ErasePage(addr) )   //modified by Dylan 20181229
	{
		ret = 1;
	}

	return ret;
}

////////////////////////////////////////////////////////////////////////////////////////////

/*******************************************************************************
@brief : flash read
@param : block   
	 offset   
	 size     
	 buf  
@ret   : (adr+sz) - OK, Failed Address -Fail
@tips  : csa37fx60 512 Bytes/section 
*******************************************************************************/
uint32_t hal_flash_read(uint16_t block, uint16_t offset, uint16_t size, uint8_t *buf)
{
	uint32_t ret ;

	uint32_t addr = ( (uint32_t)(block) << 9)+ offset;

	ret = FMC_ReadPage(addr,size,buf);

	return ret;
}

/*******************************************************************************
@brief : flash write
@param : block   
	 offset   
	 size     
	 buf  
@ret   : 0 success     1 fail
@tips  : csa37fx61 512 Bytes/section 
*******************************************************************************/
uint32_t hal_flash_write(uint16_t block, uint16_t offset, uint16_t size, uint8_t *buf)
{
	uint32_t ret;

	uint32_t addr = ((uint32_t)(block) << 9) + offset ;

	ret = FMC_WritePage(addr,size,buf) ;

	return ret;
}


